package com.test.jms.topic;

import java.util.Hashtable;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicConnectionFactory;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class ReportSubscriber implements MessageListener {

	TopicConnection topicConnection;
	TopicSession topicSession;
	TopicSubscriber topicSubscriber;
	Topic topic;

	public ReportSubscriber(String factoryJNDI, String topicJNDI) throws NamingException, JMSException {

		Hashtable<String, String> props = new Hashtable<String, String>();
		props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
		props.put(Context.PROVIDER_URL, "localhost:1099");
		props.put("java.naming.rmi.security.manager", "yes");
		props.put(Context.URL_PKG_PREFIXES, "org.jboss.naming");

		Context context = new InitialContext(props);
		TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) context.lookup(factoryJNDI);
		topicConnection = topicConnectionFactory.createTopicConnection();
		topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
		topic = (Topic) context.lookup(topicJNDI);
		topicSubscriber = topicSession.createSubscriber(topic);
		topicSubscriber.setMessageListener(this);
		System.out.println("ReportSubscriber subscribed to topic: " + topicJNDI);
		topicConnection.start();
	}

	public void onMessage(Message msg) {
		TextMessage tm = (TextMessage) msg;
		try {
			System.out.println("Got a message:" + tm.getText());
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

	public void close() throws JMSException {
		topicSession.close();
		topicConnection.close();
	}

	public static void main(String[] args) {
		try {
			ReportSubscriber subscriber = new ReportSubscriber(ReportMessagePublisher.CONNECTION_FACTORY, "/topic/InjectorTopic");
			Thread.sleep(1000 * 60 * 3);
		} catch (Exception ex) {
			System.err.println("An exception occurred while testing ReportSubscriber: " + ex);
			ex.printStackTrace();
		}
	}

}
